package com.biostime.dingdingbox.common.ueditor.upload;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.json.JSONException;
import org.json.JSONObject;

import com.biostime.dingdingbox.common.ueditor.define.State;

public class Uploader {
	private HttpServletRequest request = null;
	private Map<String, Object> conf = null;
	private static String fileName;
	public static List<String> fileNameList = new ArrayList<String>();

	public Uploader(HttpServletRequest request, Map<String, Object> conf) {
		this.request = request;
		this.conf = conf;
	}

	public final State doExec() {
		String filedName = (String) this.conf.get("fieldName");
		State state = null;

		if ("true".equals(this.conf.get("isBase64"))) {
			state = Base64Uploader.save(this.request.getParameter(filedName),
					this.conf);
		} else {
			state = BinaryUploader.save(this.request, this.conf);
		}
		
		Map<String,Object> map = toMap(state.toJSONString());
		if(map != null){
			if((String) map.get("url") != null){
				fileName = (String) map.get("url"); 
				fileNameList.add(fileName);
			}
		}

		return state;
	}
	
	/**
     * 将Json对象转换成Map
     * @param jsonObject
     * @return Map对象
     * @throws JSONException
     */
    public static Map<String,Object> toMap(String jsonString){

        JSONObject jsonObject = new JSONObject(jsonString);
        
        Map<String,Object> result = new HashMap<String,Object>();
        Iterator<?> iterator = jsonObject.keys();
        String key = null;
        
        while (iterator.hasNext()) {

            key = (String) iterator.next();
            try{
                result.put(key,  jsonObject.getInt(key));
            }catch(Exception e){
            	 result.put(key,  jsonObject.getString(key));
            }
            
        }
        return result;
    }				

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public Map<String, Object> getConf() {
		return conf;
	}

	public void setConf(Map<String, Object> conf) {
		this.conf = conf;
	}

	public static String getFileName() {
		return fileName;
	}

	public static void setFileName(String fileName) {
		Uploader.fileName = fileName;
	}
	
	
	
}
